﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using NB.MGJ.Model;
using NB.MGJ.Common.Helper;
using System.Web.Script.Serialization;
using NB.MGJ.Common.Utility;
using NB.MGJ.Service;
using NB.MGJ.Common.Cache;
using NB.MGJ.Cache;
using NB.MGJ.Common;
using NB.MGJ.Model.CodeManage;

namespace NB.MGJ.Web.Controllers
{
    /// <summary>
    /// 用户管理相关
    /// </summary>
    /// =======================================================================
    /// 类名：ManagerController ManagerController的备注：ManagerController~1<br/>
    /// =======================================================================<br/>
    /// 更新履历<br/>
    /// 序号          更新日期          责任人           更新内容<br/>
    /// 001           2017/8/16      詹善福             新建<br/>
    /// 002           201712/10         huajun             修改GetRoleInfo
    /// =======================================================================<br/>
    public partial class ManagerController
    {
        #region 角色管理
        public ActionResult RoleManage()
        {
            ViewBag.UserId = LogOnUser.UserID;
            return View();
        }

        //-------------------代码改下      V_Organization这处被我改了  这个界面视图实体  不要轻易调用  调用Organization_Enterprise就好------------------------------
        public ActionResult AddRole()
        {
            return View();
        }

        /// <summary>
        /// 修改：
        /// 注释部份不需要代码
        /// Pass 1
        /// </summary>
        public ActionResult EditRole(int? id)
        {
            if (id.HasValue)
            {
                Sys_Role organ = _mservice.GetRoleToIdService(id.Value);
                //List<Organization_Enterprise> result = _mservice.GetOrganizationService();
                //List<SelectListItem> items = new List<SelectListItem>();
                //items.AddRange(result.Select(p =>
                // {
                //     return new SelectListItem
                //     {
                //         Text = p.EnterpriseName,
                //         Value = p.ID.ToString(),
                //         Selected = organ.EnterpriseId == p.ID
                //     };
                // }));
                //ViewData["EnterpriseId"] = items;
                ViewBag.Role = organ;
            }
            return View();
        }


        /// <summary>
        /// 查询角色
        /// 审核意见：自己调整 2017年12月12日17:31:27
        /// </summary>
        public JsonResult GetRoleInfo(DetailSearch Smodel,int pageIndex = 1, int pageSize = 10)
        {
            PagerModel pm = new PagerModel();
            pm.Page = pageIndex;
            pm.PageSize = pageSize;
            if (LogOnUser.Distributor != 0)//经销商
            {
                pm.StrCondition = "  ChangeLoginID=" + LogOnUser.UserID;
            }
            else
            {
                if (LogOnUser.EnterpriseId != 1)
                {
                    //条件 本级机构和下级机构
                    pm.StrCondition = "  EnterpriseId in (" + LogOnUser.EnterpriseId + ")";
                    //根据服务版本 显示跟服务版本关联的系统默认角色
                    pm.StrCondition += string.Format(@" or id in( select roleid from sys_VersionsRole where versionsRoleID in({0}))",LogOnUser.RoleID);
                }
                else
                {
                    pm.StrCondition = "  1=1  ";
                }
            }
          
            //string where=string.Empty;

            //if (Smodel.RoleType=="系统预定义")
            //{
            //    where = "  and ( RoleName like '%" + Smodel.RoleType + "%' or RoleType=0 )";
            //}
            //else if (Smodel.RoleType == "企业自定义")
            //{
            //    where = "  and ( RoleName like '%" + Smodel.RoleType + "%' or RoleType=1 )";
            //}
            //else
            //{
            //    where = " and  RoleName like '%" + Smodel.RoleType + "%' ";
            //}

            //pm.StrCondition += where;
            var result = _mservice.GetRoleInfoService(Smodel,ref pm);
            return Json(result,JsonRequestBehavior.AllowGet);
        }

        #region 导出EXCEL
        //Pass 1
        public ActionResult ExportE(string key)
        {
            var model = _mservice.GetAllRole(key);
            var _byte_catch = Excel.Exprot<Sys_Role>(model.ToList(),
            new string[] { "角色名称", "角色类型", "关联机构类型", "备注" },
            q =>
            {
                return new object[] { 
		                  q.RoleName,
		                  q.RoleType,
		                  q.EnterpriseName,
		                  q.Remark
				};
            }, "Role");
            return File(_byte_catch, "application/octet-stream", string.Format("{0}.xlsx", DateTime.Now.ToString("yyyyMMddHHmmssfff")));
        }
        #endregion

        /// <summary>
        /// 查询当前用户  机构全部角色
        /// </summary>
        /// <returns></returns>
        public JsonResult GetRoleAll()
        {
            List<V_Role> list = new List<V_Role>();
            if (LogOnUser.Distributor != 0)//经销商
            {
                list = _mservice.GetRoleAllService(LogOnUser.EnterpriseId, LogOnUser.UserID);
            }
            else
            {
                list = _mservice.GetRoleAllService(LogOnUser.EnterpriseId,LogOnUser.RoleID);
            }
            return Json(list);
        }

        /// <summary>
        /// 删除角色
        /// Pass 1
        /// </summary>
        public JsonResult DeleteRoleInfo(int id)
        {
            var result = _mservice.DeleteRoleInfoService(id);
            return Json(result);
        }

        /// <summary>
        /// 添加角色
        /// 代码审核：不通过，存在不必要转换 2017年12月12日16:57:25
        /// </summary>
        [HttpPost]
        public JsonResult AddRoleInfo(Sys_Role Role)
        {
            Sys_Role sr = new Sys_Role();
            sr.EnterpriseId = LogOnUser.EnterpriseId;
            sr.RoleName = Role.RoleName;
            sr.ViewDel = 0;
            sr.ViewFlag = 1;
            sr.Remark = Role.Remark;
            sr.RoleType = 1;
            sr.ChangeDate = DateTime.Now;
            sr.ChangeLoginID = LogOnUser.UserID;
            var result = _mservice.AddRoleInfoService(sr);
            return Json(result);
        }
      
        /// <summary>
        /// 更新角色信息
        /// Pass 1
        /// </summary>
        public JsonResult UpdateRoleInfo(Sys_Role Role)
        {
            Role.Remark = Role.Remark ?? " ";
            var result = _mservice.UpdateRoleInfoService(Role);
            return Json(result);
        }

        /// <summary>
        /// 更新角色权限
        /// 修改 JavaScriptSerializer 为 JsonConvert.DeserializeObject  2017年12月12日17:59:33
        /// 修改 数据更新方式 2017年12月12日21:41:10
        /// Pass 1
        /// </summary>
        public int UpdateRoleMenuInfo(int id, string jsonData)
        {
            try
            {
                _mservice.DelRoleMenu(id);
                Sys_Role Role = new Sys_Role();
               jsonData= jsonData.Length> 1 ? jsonData : "";
               List<sys_MenuRoleInfo> list = Newtonsoft.Json.JsonConvert.DeserializeObject<List<sys_MenuRoleInfo>>(jsonData);
              
                //foreach (sys_MenuRoleInfo item in list)
                //{
                //    item.Id = null;
                //    item.Rid = id;
                //    _mservice.AddMenuRoleInfoService(item);
                //}
                _mservice.AddMenuRoleInfoService(list, id);
                return 1;
            }
            catch
            {
                return 0;
            }
        }

        /// <summary>
        /// 删除角色关联的菜单
        /// </summary>
        /// <returns></returns>
        public ActionResult AEditUser()
        {          
            ViewBag.uid = LogOnUser.UserID;
            return View();
        }


        #endregion

        #region 菜单管理
        public ActionResult MenuManage()
        {
            return View();
        }
        public ActionResult AddMenu(int? id)
        {

            if (id == null)
            {
                id = 0;
            }
            List<Sys_Menu> result = _mservice.GetMenuService();
            List<SelectListItem> items = new List<SelectListItem>();
            SelectListItem it = new SelectListItem() { Text = "无", Value = "0" };
            items.Add(it);
            for (int i = 0; i < result.Count; i++)
            {
                SelectListItem item = new SelectListItem() { Text = result[i].MenuName, Value = result[i].ID.ToString() };
                if (id == result[i].ID)
                {
                    item.Selected = true;
                }
                items.Add(item);
            }
            ViewData["ParentId"] = items;
            return View();

        }
        public ActionResult EditMenu(int? id)
        {
            Sys_Menu menu = _mservice.GetMenuToIdService((int)id);
            List<Sys_Menu> result = _mservice.GetMenuService();
            List<SelectListItem> items = new List<SelectListItem>();
            SelectListItem it = new SelectListItem() { Text = "无", Value = "0" };
            if (menu.ParentId == 0)
            {
                it.Selected = true;
            }
            items.Add(it);
            for (int i = 0; i < result.Count; i++)
            {
                SelectListItem item = new SelectListItem() { Text = result[i].MenuName, Value = result[i].ID.ToString() };
                if (menu.ParentId == result[i].ID)
                {
                    item.Selected = true;
                }
                items.Add(item);
            }
            ViewData["ParentId"] = items;
            ViewBag.Menu = menu;
            return View();
        }

        public ActionResult CheckMenu()
        {
            return View();
        }

        /// <summary>
        /// 查询子菜单
        /// </summary>
        /// <param name="ParentId"></param>
        /// <returns></returns>
        public JsonResult GetMenuInfo(int ParentId)
        {

            //  CacheManager.Remove(CacheKey.Key_AllMenuInfoList);
            var result = _mservice.GetMenuInfoService(ParentId);
            return Json(result);
        }


        /// <summary>
        /// 删除菜单
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public JsonResult DeleteMenuInfo(int id)
        {
            var result = _mservice.DeleteMenuInfoService(id);
            return Json(result);
        }
        /// <summary>
        /// 添加菜单
        /// </summary>
        /// <param name="Role"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult AddMenuInfo(Sys_Menu Menu)
        {
            var result = _mservice.AddMenuInfoService(Menu);
            //var ip = HttpContext.Current.Request.UserHostAddress;
            return Json(result);
        }

        /// <summary>
        /// 更新菜单
        /// </summary>
        /// <param name="Role"></param>
        /// <returns></returns>
        public JsonResult UpdateMenuInfo(Sys_Menu Menu)
        {
            var result = _mservice.UpdateMenuInfoService(Menu);
            return Json(result);
        }
        #endregion

        #region 日志管理
        public ActionResult LogManage()
        {
            return View();
        }
        public ActionResult AddLog()
        {
            return View();
        }
        /// <summary>
        /// 查询日志
        /// </summary>
        /// <param name="ParentId"></param>
        /// <returns></returns>
        public JsonResult GetLogInfo(DetailSearch Smodel, int pageIndex = 1,int PageSize = 10)
        {
            PagerModel pm = new PagerModel();
            pm.Page = pageIndex;
            pm.PageSize = PageSize;
            //pm.StrCondition = LogSearch != null ? " UserName like '%" + LogSearch + "%' " : LogSearch;
            var result = _mservice.GetLogInfoService(ref pm, LogOnUser.UserID, Smodel);
            return Json(result,JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 导出EXCEL
        public ActionResult ExportLog(DetailSearch Smodel)
        {
            var model = _mservice.GetAllLog(Smodel);
            var _byte_catch = Excel.Exprot<L.EntityModel.Sys_Log>(model.ToList(), new string[] { "操作类型", "操作说明", "操作内容", "操作人", "操作人IP", "操作时间" }, q =>
            {
                return new object[] { 
		             q.LogTypeName,
		             q.LogName,
		             q.Contents,
		             q.UserName,
		             q.LogIp,
		             q.CreatTime
				};
            }, "Log");
            return File(_byte_catch, "application/octet-stream", string.Format("{0}.xlsx", DateTime.Now.ToString("yyyyMMddHHmmssfff")));
        }
        #endregion

        #region 机构收发货地址

        public ActionResult SendReceiveAddress(int? id)
        {
            if (id.HasValue)
            {
                ViewBag.id = id.Value;
            }
            return View();
        }
        /// <summary>
        /// 根据机构查询收货地址
        /// </summary>
        /// <param name="EID">机构ID</param>
        /// <param name="CollectSendType">收发货地址类型</param>
        /// <returns></returns>
        public JsonResult GetSendInfo(int EID, int CollectSendType)
        {
            var result = _mservice.GetSendInfoService(EID, CollectSendType);
            return Json(result, JsonRequestBehavior.AllowGet);
        }
        public JsonResult AddSendInfo(organization_collectsendgoods send)
        {
            int result;
            //如果ID 为0 就新增  否则为编辑
            if (send.ID == 0)
            {
                send.ViewDel = 0;
                result = _mservice.AddSendInfoService(send);
            }
            else
            {
                result = _mservice.EditSendInfoSerice(send);
            }
            return Json(result);
        }
        public JsonResult DelSendInfo(int? ID)
        {
            int result = 0;
            if (ID.HasValue)
            {
                result = _mservice.DelSendInfoSerice(ID.Value);
            }
            return Json(result);
        }        
        public ActionResult AddReAddress(int? ID)
        {
            if (!ID.HasValue)
            {
                ID = 0;
            }
            organization_collectsendgoods send = _mservice.GetSendInfoByIDService(ID.Value);
            //如果查出来有值则此为编辑页面 否则为新增页面
            if (send == null)
            {
                send = new organization_collectsendgoods();
                WipeNullHelper.WipeNull<organization_collectsendgoods>(send);
            }
            ViewBag.send = send;
            return View();
        }
        public ActionResult AddSendAddress(int? ID)
        {
            if (!ID.HasValue)
            {
                ID = 0;
            }
            organization_collectsendgoods send = _mservice.GetSendInfoByIDService(ID.Value);
            if (send == null)
            {
                send = new organization_collectsendgoods();
                WipeNullHelper.WipeNull<organization_collectsendgoods>(send);
            }
            ViewBag.send = send;
            return View();
        }
        public ActionResult ExeclExporSend(int EID, int CollectSendType)
        {
            var model = _mservice.GetSendInfoService(EID, CollectSendType);
            var _byte_catch = Excel.Exprot<organization_collectsendgoods>(model, new string[] { "发货人", "省", "市", "区", "详细地址", "邮编","手机" }, q =>
            {
                return new object[] { 
		q.Person,
		q.ProvinceName,
		q.CityName,
		q.RegionName,
		q.Address,
		q.ZipCode,
        q.Mobile
				};
            },CollectSendType==0?"收货地址":"发货地址");
            return File(_byte_catch, "application/octet-stream", string.Format("{0}.xls", DateTime.Now.ToString("yyyyMMddHHmmssfff")));
        }
        #endregion
    }
}
